package fer

import (
	"context"
	"time"

	"gitee.com/k3x/urlx"
	"gitee.com/k3x/urlx/codec/json"
)

func FromCMB(ctx context.Context) (result Rates, err error) {
	defer result.SetDuration(time.Now())
	result.From = "招商银行"

	var out struct {
		Status int64 `json:"status"`
		Data   []struct {
			Name            string `json:"ZCcyNbr"`
			BuyingRate      string `json:"ZRthBid"`
			CashBuyingRate  string `json:"ZRtcBid"`
			SellingRate     string `json:"ZRthOfr"`
			CashSellingRate string `json:"ZRtcOfr"`
			MiddleRate      string `json:"ZRtbBid"`
		} `json:"data"`
		Ctime string `json:"ctime"`
	}

	referer := urlx.Referer("http://m.cmbchina.com/Rate/FxRealrate.aspx")
	url := "http://m.cmbchina.com/api/rate/getfxrate"
	err = urlx.IPhoneEdge(ctx).HeaderWith(referer).Url(url).Process(json.Decode(&out))

	if err != nil {
		return
	}

	result.UpdateAt, _ = time.ParseInLocation("2006-01-02 15:04", out.Ctime, locCST)
	result.Data = make(map[string]Rate, len(out.Data))
	if len(out.Data) > 0 {
		for _, item := range out.Data {
			currency := GetCode(item.Name)
			result.Data[currency] = Rate{
				Name:            item.Name,
				Currency:        currency,
				BuyingRate:      parseFloat(item.BuyingRate),
				CashBuyingRate:  parseFloat(item.CashBuyingRate),
				SellingRate:     parseFloat(item.SellingRate),
				CashSellingRate: parseFloat(item.CashSellingRate),
				MiddleRate:      parseFloat(item.MiddleRate),
			}
		}
	}

	return
}
